package wyh.controller.User;

import com.fasterxml.jackson.databind.ObjectMapper;
import wyh.pojo.User;
import wyh.service.UserService;
import wyh.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/User/validate")
public class ValidateUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = null;
        try {
            // 从请求体中读取用户信息
            user = objectMapper.readValue(req.getInputStream(), User.class);
        } catch (IOException e) {
            // 处理读取请求体时的异常
            Result result = new Result(400, "请求数据格式错误", null);
            String jsonResult = objectMapper.writeValueAsString(result);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(jsonResult);
            return;
        }
        UserService service = new UserService();
        User validatedUser = null;
        try {
            // 调用服务层的验证方法
            validatedUser = service.ServicevalidateUser(user.getUsername(), user.getPassword());
        } catch (Exception e) {
            // 处理验证过程中的异常
            Result result = new Result(500, "验证用户账号时发生错误", null);
            String jsonResult = objectMapper.writeValueAsString(result);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(jsonResult);
            return;
        }
        Result result = null;
        if (validatedUser != null) {
            // 验证成功
            result = new Result(200, "登录成功", validatedUser);
        } else {
            // 验证失败
            result = new Result(401, "用户名或密码错误", null);
        }
        String jsonResult = objectMapper.writeValueAsString(result);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(jsonResult);
    }
}